package biznussoft.metercor.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TableLayout;
import biznussoft.metercor.HomeActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.adapter.StockTransferAdapter;
import biznussoft.metercor.listeners.GlobalListener;
import biznussoft.metercor.model.Bean_Class;
import biznussoft.metercor.model.ItemModel;
import biznussoft.metercor.model.SiteModel;
import biznussoft.metercor.model.StockTransferLine;
import biznussoft.metercor.model.StockTransferModel;

import com.google.gson.Gson;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class StockTransferFragment  extends BaseFragment implements OnItemClickListener {
	private RestClient client;
	public ArrayList<ItemModel> itemList;
	public static ArrayList<SiteModel> siteList;
	public static ArrayList<StockTransferModel> stockList;
	static HashMap<String,ArrayList<StockTransferLine>> stockTransferLineMap;
	ArrayList<StockTransferLine> stockTransferLineList;
	private GlobalListener mHomeItemListener;
	private ListView lv;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.stock_transfer_fragment, null);
	}         


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);

	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);


		MenuItem actionItem = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(actionItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		actionItem.setIcon(R.drawable.logout);
		MenuItem newItem = menu.add("Stock Transfer");                 
		MenuItemCompat.setShowAsAction(newItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		newItem.setIcon(R.drawable.add); 
		

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if(item.getTitle().equals("Logout")){
			SalesforceSDKManager.getInstance().logout(getActivity());}
		if(item.getTitle().equals("Stock Transfer")){
			setHasOptionsMenu(false);
			mHomeItemListener.onServiceClicked(0);
			}
		return super.onOptionsItemSelected(item);
	}
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mHomeItemListener = (GlobalListener) (activity);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		lv = (ListView) getView().findViewById(R.id.listview);
		
		lv.setOnItemClickListener(this);
		client =  HomeActivity.mActivity.client;
		Bean_Class.api_Version = getString(R.string.api_version);

		Task task = new Task();
		task.execute();        

	}

	class Task extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			retriveLeads();
			return null;
		}

	}

	public void retriveLeads()        
	{
		try{
			String accounts = "Select id,Name,FConnect__Source_Location__c,FConnect__Destination_Location__c,FConnect__Additional_Information__c,(Select Id,Name,FConnect__Inventory_No__c,FConnect__Item__c,FConnect__Serial_ID__c,FConnect__Lot_ID__c,FConnect__Qty_Transferred__c,FConnect__Posted_To_Inventory__c,FConnect__Request_Date__c from FConnect__Stock_Transfer_Lines__r) from FConnect__Stock_Transfer__c";

			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {          
						Log.i("NCS","RestResponse   is  :"+result);
						JSONObject jsonObject1 = new JSONObject(result.asString());
						JSONArray jsonArray = jsonObject1.getJSONArray("records");
						stockList = new ArrayList<StockTransferModel>();
						stockTransferLineMap = new HashMap<String, ArrayList<StockTransferLine>>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							stockTransferLineList = new ArrayList<StockTransferLine>();
							if(!jsonArray.isNull(i)){
								StockTransferModel bean = _gson.fromJson(jsonArray.getString(i), StockTransferModel.class);
								stockList.add(bean);
								String ID = jsonArray.getJSONObject(i).getString("Id");
								JSONObject contacts = jsonArray.getJSONObject(i).getJSONObject("FConnect__Stock_Transfer_Lines__r");
								JSONArray contactsArray = contacts.getJSONArray("records");
								Gson contactsList_gson = new Gson();
								for(int j=0; j< contactsArray.length(); j++)
								{
									if(!contactsArray.isNull(j)){
										StockTransferLine contactbean = contactsList_gson.fromJson(contactsArray.getString(j), StockTransferLine.class);
										stockTransferLineList.add(contactbean);

									}
								}
								Log.i("NCS","Size is  :"+stockTransferLineList.size());
								stockTransferLineMap.put(ID, stockTransferLineList);
							}

						}

						showRecords();




					} catch (Exception e) {
						Log.i("NCS","Exception  1 is  :"+e.getMessage());
					}
				}

				@Override
				public void onError(Exception exception) {
					/*  Toast.makeText(MainActivity.this,
                               MainActivity.this.getString(SalesforceSDKManager.getInstance().getSalesforceR().stringGenericError(), exception.toString()),
                               Toast.LENGTH_LONG).show();*/
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}
		


		try{

			String accounts = "SELECT Name,Id FROM FConnect__Site__c";
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {
						Log.i("TPT","RestResponse   is  :"+result);

						JSONObject jsonObject1 = new JSONObject(result.asString());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						siteList = new ArrayList<SiteModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								SiteModel bean = _gson.fromJson(jsonArray.getString(i), SiteModel.class);
								siteList.add(bean);
							}
						}     


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);

				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}






		try{

			String accounts = "SELECT Name,Id,FConnect__Lot_Control__c,FConnect__Serial_Control__c FROM FConnect__Item__c";
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {


						JSONObject jsonObject1 = new JSONObject(result.asString());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						itemList = new ArrayList<ItemModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								ItemModel bean = _gson.fromJson(jsonArray.getString(i), ItemModel.class);
								itemList.add(bean);
							}
						}     


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);

				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}




	

	}


	public void showRecords(){
		StockTransferAdapter adapter = new StockTransferAdapter(getActivity(),stockList);
		lv.setAdapter(adapter);
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		setHasOptionsMenu(false);
		mHomeItemListener.onCategoryClicked(position);
	}


}

